package com.ls.rbac.security;

import com.ls.rbac.entity.Permission;
import com.ls.rbac.entity.User;
import com.ls.rbac.service.IPermissionService;
import com.ls.rbac.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * created by liush on 2025/6/27
 **/
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private IUserService userService;
    @Resource
    private IPermissionService permissionService; // 权限服务，查询当前用户对应的权限
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Permission> permissionList= permissionService.selectPermissionListByUserId(user.getId());


        List<String> permissionCodeList = permissionList.stream()
                .filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .filter(Objects::nonNull).toList();
        String[] array=permissionCodeList.toArray(new String[0]);
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorities);
        return user;
    }

}
